//
//  NSObject+Extension.m
//  UIWebView
//
//  Created by Hello Cai on 2017/6/19.
//  Copyright © 2017年 keisun. All rights reserved.
//

#import "NSObject+Extension.h"

@implementation NSObject (Extension)


-(id)performSelector:(SEL)aSelector withObjects:(NSArray *)objects{
    //方法签名
    /*
     sinature有个_reserved的指针数组，第一个元素打印为：v@:@@@。与NSInvocation有关（这里是三个参数获取的结果）
     */
    NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:aSelector];
    if (signature == nil) {
        return nil;
    }
    
    //NSInvocation : 利用一个NSInvocation对象包装一次方法调用（方法调用者、方法名、方法参数、方法返回值）
    /*（这里是三个参数获取的结果）
     return value: {v} void
     target:       {@} 0x0
     selector:     {:} null
     argument 2:   {@} 0x0
     argument 3:   {@} 0x0
     argument 4:   {@} 0x0
     */
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
    invocation.target = self;
    invocation.selector = aSelector;
    
    for (int i=0; i<objects.count; i++) {
        id object = objects[i];
        if ([object isKindOfClass:[NSNull class]]) continue;
        [invocation setArgument:&object atIndex:i+2];
    }
    
    //调用方法
    [invocation invoke];
    
    //获取返回值
    id returnValue = nil;
    if (signature.methodReturnLength) { // 有返回值类型，才去获得返回值
        [invocation getReturnValue:&returnValue];
    }
    return returnValue;
}
@end
